package com.nbsaas.boot.controller.web;

import com.nbsaas.boot.rest.response.ResponseObject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.Instant;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.Map;

@RestController
public class UpdateController {

    private static final String MINIO_DOWNLOAD_URL = "http://front.xabaison.com/minio.jar";
    private static final String CLOUD_DIR = "/data/cloud";
    private static final String SHELL_DIR = "/data/shell";
    private static final String MINIO_FILE_PATH = CLOUD_DIR + "/minio.jar";
    private static final String PRODUCT_SCRIPT_PATH = SHELL_DIR + "/product.sh";

    /**
     * 更新版本
     *
     * @return 更新结果
     */
    @PostMapping("/updateVersion")
    public ResponseObject<Map<String, Object>> updateVersion() {
        ResponseObject<Map<String, Object>> result = new ResponseObject<>();
        Map<String, Object> updateInfo = new HashMap<>();
        
        try {
            // 1. 创建必要的目录
            createDirectories();
            
            // 2. 下载minio.jar文件
            boolean downloadSuccess = downloadMinioFile();
            updateInfo.put("downloadSuccess", downloadSuccess);
            
            if (downloadSuccess) {
                // 3. 验证文件下载
                FileInfo fileInfo = verifyDownloadedFile();
                updateInfo.put("fileInfo", fileInfo);
                
                // 4. 执行product.sh脚本
                boolean scriptExecuted = executeProductScript();
                updateInfo.put("scriptExecuted", scriptExecuted);
                
                result.setCode(200);
                result.setMsg("版本更新成功");
            } else {
                result.setCode(500);
                result.setMsg("文件下载失败");
            }
            
        } catch (Exception e) {
            result.setCode(500);
            result.setMsg("版本更新失败: " + e.getMessage());
            updateInfo.put("error", e.getMessage());
        }
        
        result.setData(updateInfo);
        return result;
    }

    /**
     * 获取版本更新状态
     */
    @GetMapping("/versionStatus")
    public ResponseObject<Map<String, Object>> getVersionStatus() {
        ResponseObject<Map<String, Object>> result = new ResponseObject<>();
        Map<String, Object> status = new HashMap<>();
        
        try {
            // 检查文件是否存在
            File minioFile = new File(MINIO_FILE_PATH);
            File scriptFile = new File(PRODUCT_SCRIPT_PATH);
            
            status.put("minioFileExists", minioFile.exists());
            status.put("scriptFileExists", scriptFile.exists());
            
            if (minioFile.exists()) {
                status.put("minioFileSize", minioFile.length());
                status.put("minioFileLastModified", 
                    LocalDateTime.ofInstant(Instant.ofEpochMilli(minioFile.lastModified()), ZoneId.systemDefault())
                        .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            }
            
            result.setCode(200);
            result.setMsg("获取状态成功");
            
        } catch (Exception e) {
            result.setCode(500);
            result.setMsg("获取状态失败: " + e.getMessage());
            status.put("error", e.getMessage());
        }
        
        result.setData(status);
        return result;
    }

    /**
     * 创建必要的目录
     */
    private void createDirectories() throws IOException {
        Files.createDirectories(Paths.get(CLOUD_DIR));
        Files.createDirectories(Paths.get(SHELL_DIR));
    }

    /**
     * 下载minio.jar文件
     */
    private boolean downloadMinioFile() {
        try {
            URL url = new URL(MINIO_DOWNLOAD_URL);
            Path targetPath = Paths.get(MINIO_FILE_PATH);
            
            // 下载文件，如果存在则覆盖
            Files.copy(url.openStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);
            
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 验证下载的文件
     */
    private FileInfo verifyDownloadedFile() {
        FileInfo fileInfo = new FileInfo();
        File file = new File(MINIO_FILE_PATH);
        
        if (file.exists()) {
            fileInfo.setExists(true);
            fileInfo.setSize(file.length());
            fileInfo.setLastModified(file.lastModified());
            fileInfo.setPath(file.getAbsolutePath());
        } else {
            fileInfo.setExists(false);
        }
        
        return fileInfo;
    }

    /**
     * 执行product.sh脚本
     */
    private boolean executeProductScript() {
        try {
            File scriptFile = new File(PRODUCT_SCRIPT_PATH);
            
            if (!scriptFile.exists()) {
                // 如果脚本不存在，创建一个简单的脚本
                createDefaultScript();
            }
            
            // 在Windows环境下，尝试使用PowerShell执行
            ProcessBuilder processBuilder = new ProcessBuilder();
            
            if (System.getProperty("os.name").toLowerCase().contains("windows")) {
                processBuilder.command("powershell", "-Command", 
                    "if (Test-Path '" + PRODUCT_SCRIPT_PATH + "') { & '" + PRODUCT_SCRIPT_PATH + "' } else { Write-Host 'Script not found' }");
            } else {
                processBuilder.command("bash", PRODUCT_SCRIPT_PATH);
            }
            
            Process process = processBuilder.start();
            int exitCode = process.waitFor();
            
            return exitCode == 0;
            
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 创建默认脚本
     */
    private void createDefaultScript() throws IOException {
        String scriptContent = "#!/bin/bash\n" +
                "echo \"Product script executed at $(date)\"\n" +
                "echo \"Minio file path: " + MINIO_FILE_PATH + "\"\n" +
                "if [ -f \"" + MINIO_FILE_PATH + "\" ]; then\n" +
                "    echo \"Minio file exists with size: $(stat -c%s " + MINIO_FILE_PATH + ") bytes\"\n" +
                "else\n" +
                "    echo \"Minio file not found\"\n" +
                "fi\n" +
                "echo \"Script execution completed\"\n";
        
        Path scriptPath = Paths.get(PRODUCT_SCRIPT_PATH);
        Files.write(scriptPath, scriptContent.getBytes());
        
        // 设置执行权限（在Unix系统上）
        if (!System.getProperty("os.name").toLowerCase().contains("windows")) {
            scriptPath.toFile().setExecutable(true);
        }
    }

    /**
     * 文件信息类
     */
    public static class FileInfo {
        private boolean exists;
        private long size;
        private long lastModified;
        private String path;

        // Getters and Setters
        public boolean isExists() { return exists; }
        public void setExists(boolean exists) { this.exists = exists; }
        
        public long getSize() { return size; }
        public void setSize(long size) { this.size = size; }
        
        public long getLastModified() { return lastModified; }
        public void setLastModified(long lastModified) { this.lastModified = lastModified; }
        
        public String getPath() { return path; }
        public void setPath(String path) { this.path = path; }
    }
}
